package minuy.android.slowcarremotecontrol;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;


import minuy.android.slowcarremotecontrol.service.BluetoothService;
import minuy.android.slowcarremotecontrol.service.ViewService;
import minuy.android.slowcarremotecontrol.tool.Constant;
import minuy.android.slowcarremotecontrol.tool.HanderHelper;
import minuy.android.slowcarremotecontrol.tool.SPHelper;
import minuy.android.slowcarremotecontrol.view.VerticalSeekBar;

public class MainActivity extends Activity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    VerticalSeekBar vsbR,vsbL,vsbRS,vsbLS;
    TextView tvCLS,tvCRS,tvCL,tvCR,tvRsta,tvLsta,tvSta,tvBluetoothInfo;
    EditText etInfo;
    Button btnLink,btnHelp;
    Switch swLock;

    private SPHelper spHelper;

    ViewService viewService;
    HanderHelper handerHelper;
    BluetoothService bluetoothService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spHelper = SPHelper.getInstant(getApplicationContext());
        handerHelper = HanderHelper.getHanderHelper();
        handerHelper.setHander(handler);

        swLock = findViewById(R.id.swLock);

        vsbR = findViewById(R.id.vsbR);//右速度
        vsbL = findViewById(R.id.vsbL);//左速度
        vsbRS = findViewById(R.id.vsbRS);//右方向
        vsbLS = findViewById(R.id.vsbLS);//左方向

        tvSta = findViewById(R.id.tvSta);
        tvCLS = findViewById(R.id.tvCLS);
        tvCRS = findViewById(R.id.tvCRS);
        tvCL = findViewById(R.id.tvCL);
        tvCR = findViewById(R.id.tvCR);
        tvRsta = findViewById(R.id.tvRsta);
        tvLsta = findViewById(R.id.tvLsta);
        tvBluetoothInfo = findViewById(R.id.tvBluetoothInfo);

        etInfo = findViewById(R.id.etInfo);

        btnLink = findViewById(R.id.btnLink);
        btnHelp = findViewById(R.id.btnHelp);

        //初始化视图
        swLock.setOnClickListener(this);

        btnHelp.setOnClickListener(this);
        btnLink.setOnClickListener(this);

        vsbR.setOnSeekBarChangeListener(this);
        vsbL.setOnSeekBarChangeListener(this);
        vsbRS.setOnSeekBarChangeListener(this);
        vsbLS.setOnSeekBarChangeListener(this);

        viewService = new ViewService(getApplication());
        bluetoothService = BluetoothService.getBluetoothService();

        swLock.setChecked(spHelper.getBooleanFromSP(getApplication(), Constant.SW_LOCK,false));
        if(swLock.isChecked()){
            viewService.setLock(swLock.isChecked());
            vsbL.setEnabled(!swLock.isChecked());
        }

        vsbR.setProgress(100);//右速度
        vsbL.setProgress(100);//左速度
        vsbRS.setProgress(50);//右方向
        vsbLS.setProgress(50);//左方向

        bluetoothService.Init(getApplication());
    }



    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btnHelp){
            //帮助按钮
            AlertDialog.Builder builder  = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("帮助" );
            builder.setMessage(strHelp) ;
            builder.setPositiveButton("好" ,  null );
            builder.show();
        }else if(v.getId() == R.id.btnLink){
            //连接按钮
            Toast.makeText(getApplication(),"准备连接蓝牙……",Toast.LENGTH_SHORT).show();
            bluetoothService.BluetoothLink(this);
        }else if(v.getId() == R.id.swLock){
            //速度锁
            spHelper.putData2SP(getApplication(), Constant.SW_LOCK, swLock.isChecked());//保存设置
            vsbR.setProgress(vsbL.getProgress());//同步速度
            viewService.setLock(swLock.isChecked());

            vsbL.setEnabled(!swLock.isChecked());
        }
    }

    @Override
    public void finish() {
        super.finish();
        endProgress();
    }

    private void endProgress(){
        //左速度
        handerHelper.sendHanderMsg(Constant.SPEED_L_S,vsbL.getProgress());
        //右速度
        handerHelper.sendHanderMsg(Constant.SPEED_R_S,vsbR.getProgress());
        //左状态
        handerHelper.sendHanderMsg(Constant.STA_L_S,vsbLS.getProgress());
        //右状态
        handerHelper.sendHanderMsg(Constant.STA_R_S,vsbRS.getProgress());

        /*
        try {
            Thread.sleep(200);
            viewService.progressChanged(vsbR,vsbR.getProgress());
            Thread.sleep(200);
            viewService.progressChanged(vsbL,vsbL.getProgress());
            Thread.sleep(200);
            viewService.progressChanged(vsbRS,vsbRS.getProgress());
            Thread.sleep(200);
            viewService.progressChanged(vsbLS,vsbLS.getProgress());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
         */
    }




    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        System.out.println(fromUser);
        new Thread(){
            @Override
            public void run() {
                viewService.progressChanged(seekBar,progress);
            }
        }.start();
    }

    //再按一次退出实现
    long mExitTime;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        bluetoothService.Close();
        tvBluetoothInfo.setText("蓝牙未连接");
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {}

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {}

    Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            String lable = "";
            switch (msg.what){
                case Constant.STA://总状态更新
                    if(msg.obj != null){
                        lable = (String)msg.obj;
                        tvSta.setText(lable);
                    }
                    break;
                case Constant.STA_L://左电机状态
                    if(msg.obj != null){
                        lable = (String)msg.obj;
                        tvCLS.setText(lable);
                    }
                    break;
                case Constant.STA_R://右电机状态
                    if(msg.obj != null){
                        lable = (String)msg.obj;
                        tvCRS.setText(lable);
                    }
                    break;
                case Constant.STA_S_L://左电机状态
                    if(msg.obj != null){
                        lable = (String)msg.obj;
                        tvLsta.setText(lable);
                    }
                    break;
                case Constant.STA_S_R://右电机状态
                    if(msg.obj != null){
                        lable = (String)msg.obj;
                        tvRsta.setText(lable);
                    }
                    break;
                case Constant.SPEED_L://左电机速度
                    if(msg.obj != null){
                        lable = (String)msg.obj;
                        tvCL.setText(lable);
                    }
                    break;
                case Constant.SPEED_R://右电机速度
                    if(msg.obj != null){
                        lable = (String)msg.obj;
                        tvCR.setText(lable);
                    }
                    break;
                case Constant.EDIT://编辑框更新
                    if(msg.obj != null){
                        lable = (String)msg.obj;
                        etInfo.setText(lable);
                    }
                    break;
                case Constant.LOCK_R://电机锁更新
                    vsbR.setProgress(vsbL.getProgress());
                    break;
                case Constant.LOCK_L:
                    vsbL.setProgress(vsbR.getProgress());
                    break;
                case Constant.LOCK_SAVE:
                    spHelper.putData2SP(getApplication(), Constant.SW_LOCK, swLock.isChecked());
                    break;
                case Constant.STA_L_S:
                    spHelper.putData2SP(getApplication(),Constant.STA_LIFT,msg.arg1+"");
                    break;//左电机状态
                case Constant.STA_R_S:
                    spHelper.putData2SP(getApplication(),Constant.STA_RIGHT,msg.arg1+"");
                    break;//右电机状态
                case Constant.SPEED_L_S:
                    spHelper.putData2SP(getApplication(),Constant.SPEED_LIFT,msg.arg1+"");
                    break;//左电机速度
                case Constant.SPEED_R_S:
                    spHelper.putData2SP(getApplication(),Constant.SPEED_RIGHT,msg.arg1+"");
                    break;//右电机速度
                case Constant.BLUE_SEND:
                    bluetoothService.send((String)msg.obj);
                    break;
                case Constant.BLUETOOTH_CONNECTED://蓝牙已连接
                    btnLink.setText("已连接");
                    btnLink.setEnabled(false);
                    break;
                case Constant.BLUETOOTH_CONNECTION_FAIL://连接失败
                    btnLink.setText("连接失败");
                    btnLink.setEnabled(true);
                    break;
                case Constant.BLUETOOTH_DISCONNECTION://断开连接
                    btnLink.setText("连接断开");
                    btnLink.setEnabled(true);
                    break;
                case Constant.BLUETOOTH_RECEIVE_MSG://连接消息
                    if(msg.obj!=null) {
                        byte[] b = (byte[]) msg.obj;
                        String s = new String(b);
                        tvBluetoothInfo.setText(s);
                    }
                    break;
            }
        }
    };

    String strHelp = "为二轮51遥控车设计的蓝牙串口遥控器！\n" +
            "\n" +
            "操作说明：\n" +
            "在操作之前需要连接到小车上的蓝牙模块，否则操作是无效的。\n" +
            "蓝牙需要先在系统设置中配对成功~\n" +
            "有四根滑动条，在屏幕左右的分别控制小车的左右电机。滑动条上有文字说明的为控制电机的正转、反转和停止（横屏边缘，竖屏下面的那两条）。其他两个是控制电机的速度的，有1-30个速度档位，滑动即可向单片机发送指令（出问题尝试滑动慢点，单片机可能处理不了那么快）。速度锁是同步两个电机的速度，开启后只需要控制右边的速度滑动条即可。\n" +
            "\n" +
            "祝您身体健康，生活愉快~\n" +
            "\n" +
            "Bug反馈：\n" +
            "https://space.bilibili.com/32778000";
}